const fsPromises = require('fs').promises;
const path = require('path');
const {
    Facility,
    badFacility
} = require('../../../model/Facility');

module.exports = async (req, res) => {
    const data = req.fields;
    if (!data.title) {
        // 获取需要导入数据库的初始化数据，传入相对当前目录的文件路径
        const pokemons = JSON.parse(await fsPromises.readFile(
            path.join(__dirname, '../../../const/pokemon.json'), {
                encoding: "utf8",
                flag: "r"
            }));
        data.title = pokemons[parseInt(Math.random() * pokemons.length)];
    }
    if (badFacility(data, req, res)) return;
    let facility = await Facility.findOne(data);
    if (facility) return res.sendResult(null, 400, '已拥有的宝可梦！换一只收服吧~');

    // 创建设施
    facility = await Facility.create(data);
    // 响应
    res.sendResult(facility, 200, '添加设施成功');
};